﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemCenterSoa.BaseLibrary.Tools.TypeTools;
using SystemCenterSoa.DtoModel.Common;
using SystemCenterSoa.DtoModel.SystemManager;
using SystemCenterSoa.IRepository.SystemManager;
using SystemCenterSoa.PoModel.SystemManager;
using SystemCenterSoa.Repository.CommonLib;

namespace SystemCenterSoa.Repository.SystemManager
{
    public class RoleRepository: BaseRepository, IRoleRepository
    {
        //注入ef的的上下文
        public RoleRepository(SystemCenterDbSoaContext systemCenterDbSoaContext) : base(systemCenterDbSoaContext)
        {


        }
        /// <summary>
        /// 查询指定用户名下面的角色
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<RolePo> GetRoleDbsByUserName(string userName)
        {
            return (from r in _systemCenterDbSoaContext.RolePo
                    join arr in _systemCenterDbSoaContext.AdminUserRoleRelationPo on r.role_id equals arr.role_id
                    where arr.user_name == userName
                    select r).ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public RoleDto GetRoleViewById(int roleId)
        {
            var RolePo = _systemCenterDbSoaContext.RolePo.FirstOrDefault(c => c.role_id == roleId);
            if (RolePo == null) return null;
            RoleDto view = ModelCopier.CreateInstanceFrom<RoleDto>(RolePo);
            view.roleModuleCode = _systemCenterDbSoaContext.RoleModuleRelationPo.
                Where(c => c.role_id == roleId).Select(b => b.module_code).ToList();
            return view;

        }

        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="view">角色视图</param>
        /// <returns></returns>
        public int RoleDbAdd(RoleDto view)
        {
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    RolePo db = ModelCopier.CreateInstanceFrom<RolePo>(view);
                    _systemCenterDbSoaContext.RolePo.Add(db);
                    _systemCenterDbSoaContext.SaveChanges();//保存以后,就可以把role_id获取到
                    List<RoleModuleRelationPo> rmrs = new List<RoleModuleRelationPo>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelationPo()
                            {
                                role_id = db.role_id,
                                module_code = mc,
                                creator_date = db.creator_date,
                                creator_name = db.creator_name
                            });
                        }
                        _systemCenterDbSoaContext.RoleModuleRelationPo.AddRange(rmrs);
                        _systemCenterDbSoaContext.SaveChanges();
                    }
                    tran.Commit();
                    return db.role_id;

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }


            }



        }
        /// <summary>
        /// 因为角色修改涉及到角色表与角色模块表的修改, 所以需要先删除角色模块表, 在插入新的角色模块记录
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        public bool RoleUpdate(RoleDto view)
        {
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    var RolePo = _systemCenterDbSoaContext.RolePo.FirstOrDefault(c => c.role_id == view.role_id);
                    ModelCopier.CopyModel(view, RolePo, "creator_name", "creator_date");
                    _systemCenterDbSoaContext.SaveChanges();//保存以后
                    //efcore 的 ExecuteSqlRaw 参数化格式是 ({参数位置})
                    string delSql = " delete role_module_relation where role_id=({0})";
                    //想要efcore 执行sql  需要引入 Microsoft.EntityFrameworkCore.Relational
                    //执行删除sql
                    _systemCenterDbSoaContext.Database.ExecuteSqlRaw(delSql, RolePo.role_id);

                    List<RoleModuleRelationPo> rmrs = new List<RoleModuleRelationPo>();
                    if (view.roleModuleCode != null && view.roleModuleCode.Count > 0)
                    {
                        foreach (var mc in view.roleModuleCode)
                        {
                            rmrs.Add(new RoleModuleRelationPo()
                            {
                                role_id = RolePo.role_id,
                                module_code = mc,
                                creator_date = RolePo.modifi_date.Value,
                                creator_name = RolePo.modifi_name
                            });
                        }
                        _systemCenterDbSoaContext.RoleModuleRelationPo.AddRange(rmrs);
                        _systemCenterDbSoaContext.SaveChanges();
                    }
                    tran.Commit();
                    return true;



                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }


            }
        }

        public PagerResult<RolePo> SearchPage(SearchModel searchModel)
        {
            var query = _systemCenterDbSoaContext.RolePo.AsQueryable();
            //判断有没有搜索条件
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {
                //把搜索条件拿出来
                var tempDi = searchModel.SearchItem;

                //搜索字段为role_name
                string roleName = "role_name";
                //判断搜索条件中是否有role_name
                if (tempDi.Keys.Contains(roleName) && !string.IsNullOrEmpty(tempDi[roleName]))
                {
                    query = query.Where(c => c.role_name.Contains(tempDi[roleName]));
                }

                //搜索字段为role_status
                string roleStatus = "role_status";
                //判断搜索条件中是否有role_name
                if (tempDi.Keys.Contains(roleStatus) && !string.IsNullOrEmpty(tempDi[roleStatus]))
                {
                    int tempStatus = -1;
                    if (int.TryParse(tempDi[roleStatus], out tempStatus))
                    {
                        query = query.Where(c => c.role_status == tempStatus);
                    }

                }

                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "role_id")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_id);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_id);
                        }
                    }


                    if (searchModel.OrderBy == "role_name")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.role_name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.role_name);
                        }
                    }
                }



            }
            return BasePageSearch(query, searchModel);
        }
    }
}
